<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请名称" prop="applyName">
        <el-input
          v-model="queryParams.applyName"
          placeholder="请输入申请名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="著作权人" prop="applyUser">
        <el-input
          v-model="queryParams.applyUser"
          placeholder="请输入著作权人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="软著类型" prop="applyType">
        <el-select v-model="queryParams.applyType" placeholder="请选择软著类型" clearable>
          <el-option
            v-for="dict in rz_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="当前阶段" prop="currentFlow">
        <el-select v-model="queryParams.currentFlow" placeholder="请选择当前阶段" clearable>
          <el-option
            v-for="dict in flow_node"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:ruanzhuInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:ruanzhuInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:ruanzhuInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:ruanzhuInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruanzhuInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column type="index" label="序号" align="center" prop="id" width="50" />
      <el-table-column label="申请名称" align="center" prop="applyName" width="200" />
      <el-table-column label="著作权人" align="center" prop="applyUser">
        <template #default="scope">
          <span v-if="customUserList.length > 0">
            {{ getCustomName(scope.row.applyUser) }}
          </span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="软著类型" align="center" prop="applyType">
        <template #default="scope">
          <dict-tag :options="rz_type" :value="scope.row.applyType"/>
        </template>
      </el-table-column>
      <el-table-column label="当前阶段" align="center" prop="currentFlow">
        <template #default="scope">
          <dict-tag :options="flow_node" :value="scope.row.currentFlow"/>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :preview-teleported="true" :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="290">
        <template #default="scope">
          <el-button link type="primary" icon="Promotion" @click="handleSendSms(scope.row)" v-hasPermi="['manage:ruanzhuInfo:edit']">发短信</el-button>
          <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)" v-hasPermi="['manage:ruanzhuInfo:list']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:ruanzhuInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:ruanzhuInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改软著申请情况对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="ruanzhuInfoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请名称" prop="applyName">
          <el-input v-model="form.applyName" placeholder="请输入申请名称" />
        </el-form-item>
        <el-form-item label="著作权人" prop="applyUser">
          <el-select v-model="form.applyUser" placeholder="请选择著作权人">
            <el-option v-for="item in customUserList" :key="item.id" :label="item.customName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="软著类型" prop="applyType">
          <el-select v-model="form.applyType" placeholder="请选择软著类型">
            <el-option
              v-for="dict in rz_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前阶段" prop="currentFlow">
          <el-select v-model="form.currentFlow" placeholder="请选择当前阶段">
            <el-option
              v-for="dict in flow_node"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请通过后的图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="申请通过后的pdf文件" prop="pdfFile">
          <file-upload v-model="form.pdfFile"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 短信发送对话框 -->
     <el-dialog custom-class="smsFormLoading" v-model="smsOpen" title="短信发送">
        <el-descriptions :columns="2"  border>
          <el-descriptions-item label="接收人">
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle" style="margin-right: 10px;">
                  <user />
                </el-icon>
                接收人
              </div>
            </template>
            <el-tag v-if="form.applyUser">{{ getCustomName(form.applyUser) }}</el-tag>
            <el-tag v-else>--</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="接收人">
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle" style="margin-right: 10px;">
                  <phone />
                </el-icon>
                接收号码
              </div>
            </template>
            {{ smsForm.sendAddr ? smsForm.sendAddr : '暂无' }}
          </el-descriptions-item>
        </el-descriptions>
      <el-form style="margin-top: 20px;" ref="smsFormRef"  :model="smsForm" :rules="smsRules" label-width="80px"> 
        <el-form-item label="发送方式" prop="messageType">
          <el-radio-group @change="redioChance" v-model="smsForm.messageType">
            <el-radio label="1" border>手机短信</el-radio>
            <el-radio label="2" border>邮箱</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发送内容" prop="message"> 
          <el-button @click="handelTemplateClick" v-if="smsForm.messageType !== null" type="primary" style="margin:10px 0;">选择模板</el-button>
          <el-input v-if="smsForm.messageType === '1'" type="textarea" rows="4" v-model="smsForm.message" placeholder="请输入发送内容" />
          <editor v-if="smsForm.messageType === '2'" v-model="smsForm.message" :min-height="192"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="smsSubmit">发 送</el-button>
          <el-button @click="smsCancel">取 消</el-button>
        </div>
      </template>
     </el-dialog>

     <!-- 选择模板对话框 -->
      <el-dialog v-model="templateOpen" title="选择模板" > 
        <el-table highlight-current-row ref="templateTableRef" @select="templateSelect" :data="tempLateListFilter" border>
          <el-table-column type="selection" width="55" />
          <el-table-column label="模板名称" prop="templateName"></el-table-column>
          <el-table-column label="创建人" prop="createBy" width="100" />
          <el-table-column label="创建时间" prop="createTime" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="templateViewClick(scope.row)">查看内容</el-button>
            </template>
          </el-table-column>
        </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="templateSubmit()">确 定</el-button>
          <el-button @click="templateOpen = false">取 消</el-button>
        </div>
      </template>
     </el-dialog>

     <!-- 查看内容对话框 -->
      <el-dialog v-model="templateViewOpen" title="模板内容">
        <el-card>
          <el-input disabled v-if="smsForm.messageType === '1'" type="textarea" v-model="templateViewContent" :rows="5"></el-input>
          <div v-if="smsForm.messageType === '2'" v-html="templateViewContent"></div>
        </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="templateViewOpen = false">确 定</el-button>
        </div>
      </template>
      </el-dialog>
  </div>
</template>

<script setup name="RuanzhuInfo">
import { listRuanzhuInfo, getRuanzhuInfo, delRuanzhuInfo, addRuanzhuInfo, updateRuanzhuInfo, sendSms } from "@/api/manage/ruanzhuInfo"
import { listCustomUser } from '@/api/manage/customUser'
import { listTemplateMessage } from '@/api/manage/templateMessage'
import { ref, reactive, onMounted } from 'vue'
import { isEmptyObject } from '@/utils/object'
import { ElLoading } from 'element-plus'



const { proxy } = getCurrentInstance()
const { flow_node, rz_type } = proxy.useDict('flow_node', 'rz_type')


const ruanzhuInfoList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeCreateTime = ref([])
const customUserList = ref([])
const smsOpen = ref(false)
const iconStyle = { fontSize: '16px', color: '#409EFF' }
const templateOpen = ref(false)
const templateViewOpen = ref(false)
const templateViewContent = ref('')
const templateList = ref([])
// 经过筛选的templateList
const tempLateListFilter = ref([])
const smsFormLoading = ref(true)


const smsForm = reactive({
  applyUser: null,
  userName: null,
  messageType: null,
  sendAddr: '',
  message: ''
})

const smsRules = reactive({
  messageType: [{ required: true, message: "发送方式不能为空", trigger: "blur" } ],
  // message: [{ required: true, message: "发送消息不能为空", trigger: "blur" } ]
})

const resetSmsForm = () => {
  smsForm.applyUser = null
  smsForm.userName = null
  smsForm.messageType = null
  smsForm.sendAddr = ''
  smsForm.message = ''
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyName: null,
    applyUser: null,
    applyType: null,
    currentFlow: null,
    remark: null,
    createBy: null,
    createTime: null,
  },
  rules: {
    applyName: [
      { required: true, message: "申请名称不能为空", trigger: "blur" }
    ],
    applyUser: [
      { required: true, message: "著作权人不能为空", trigger: "blur" }
    ],
    applyType: [
      { required: true, message: "软著类型不能为空", trigger: "change" }
    ],
    currentFlow: [
      { required: true, message: "当前阶段不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 获取著作权人名称 */
const getCustomName = (userId) => {
  if (!userId) return '--'
  const user = customUserList.value.find(item => item.id === userId)
  return user ? user.customName : '--'
}

/** 查询软著申请情况列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (daterangeCreateTime.value && daterangeCreateTime.value.length > 0) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0]
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1]
  }
  
  Promise.all([
    listRuanzhuInfo(queryParams.value),
    listCustomUser(queryParams.value), 
    listTemplateMessage(queryParams.value)
  ]).then(([ruanzhuResponse, customResponse, templateRes]) => {
    ruanzhuInfoList.value = ruanzhuResponse.rows
    customUserList.value = customResponse.rows
    templateList.value = templateRes.rows
    total.value = ruanzhuResponse.total
    loading.value = false
  }).catch(error => {
    console.error('数据加载失败', error)
    proxy.$modal.msgError('数据加载失败')
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

const smsCancel = () => {
  smsOpen.value = false
  smsForm.messageType = ''
  smsForm.sendAddr = ''
}

// 表单重置
function reset(refReset = true) {
  form.value = {
    id: null,
    applyName: null,
    applyUser: null,
    applyType: null,
    currentFlow: null,
    image: null,
    pdfFile: null,
    remark: null,
    createBy: null,
    updateBy: null,
    createTime: null,
    updateTime: null
  }
  if (refReset) {
    proxy.resetForm("ruanzhuInfoRef")
  }
}

/** 发送短信的方法 */
const handleSendSms = (row) => {
  form.value = row
  smsForm.messageType = null
  smsForm.sendAddr = ''
  smsForm.applyUser = row.applyUser
  smsForm.userName = customUserList.value.filter(item => item.id === row.applyUser)[0].customName
  smsOpen.value = true
}
const smsSubmit = () => {
    let dialogLoading = ElLoading.service({
    target: '.smsFormLoading',
    Lock: true,
  })
  proxy.$refs["smsFormRef"].validate(vaild => {
    if(!vaild){
      proxy.$modal.msgError("请填写完整信息")
      dialogLoading.close()
      return false
    }
    proxy.$modal.msg("发送中...")
    sendSms(smsForm).then(res => {
      proxy.$modal.msgSuccess("发送成功")
      dialogLoading.close()
      smsOpen.value = false
      resetSmsForm()
    })
    
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加软著申请情况"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getRuanzhuInfo(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改软著申请情况"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ruanzhuInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRuanzhuInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addRuanzhuInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除软著申请情况编号为"' + row.applyName + '"的数据项？').then(function() {
    return delRuanzhuInfo(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/ruanzhuInfo/export', {
    ...queryParams.value
  }, `ruanzhuInfo_${new Date().getTime()}.xlsx`)
}

const redioChance = (value) => {
  smsForm.message = '' 
  if (!form.value.applyUser) {
    proxy.$modal.msgError('请先选择著作权人')
    smsForm.messageType = null
    return
  }
  
  const user = customUserList.value.find(item => item.id === form.value.applyUser)
  if (!user) {
    proxy.$modal.msgError('未找到该著作权人信息，请刷新页面')
    smsForm.messageType = null
    return
  }
  
  let addr = ''
  switch(value){
    case '1':
      addr = user.phone
      if(!addr) {
        proxy.$modal.msgError('当前用户还没有关联的手机号信息')
        if(smsForm.messageType !== ''){
          smsForm.messageType = '2'
        }
        return
      }
      smsForm.sendAddr = addr
      break;
    case '2':
      addr = user.email
      if(!addr) {
        proxy.$modal.msgError('当前用户还没有关联的邮箱信息')
        if(smsForm.messageType !== ''){
          smsForm.messageType = '1'
        }
        return
      }
      smsForm.sendAddr = addr
      break;
  }
}

/** 选择模板对话框start */
const templateTableRef = ref(null)
const currentSelectTemplate = ref({})
const handelTemplateClick = () => {
  currentSelectTemplate.value = {}
  templateOpen.value = true
  tempLateListFilter.value = templateList.value.filter(item => item.templateType + 1 === +smsForm.messageType)
  // templateTableRef.value?.clearSelection()
}

/** 模板选择事件处理 */
const templateSelect = (selection) => {
  currentSelectTemplate.value = selection[0]
  if (selection.length > 1) {
      let del_row = selection.shift();
      templateTableRef.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
}

// 模板列表点击了确定
const templateSubmit = () => {
  //判断一下有没有选
  if(isEmptyObject(currentSelectTemplate.value)){
    proxy.$modal.msgError("请选择模板")
    return
  }
  smsForm.message = currentSelectTemplate.value.content
  templateOpen.value = false
}

// 查看内容
const templateViewClick = (row) => {
  templateViewContent.value = row.content
  templateViewOpen.value = true
}


// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>
<style scoped>
.cell-item {
  display: flex;
  align-items: center;
}
</style>